<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>参赛报名 - 数智化赋能"微情境·微宣讲"红色实践活动</title>
    <!-- 引入Swiper CSS -->
    <link rel="stylesheet" href="../templates/h5/assets/swiper-bundle.min.css">
    <!-- 引入Tailwind CSS -->
    <script src="../templates/h5/assets/tailwindcss3.4.17.css"></script>
    <!-- 引入Font Awesome -->
    <link href="../templates/h5/assets/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        // 配置Tailwind自定义颜色（红色主题）
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#b71211', // 主红色
                        secondary: '#FFD700', // 辅助金色
                        red: {
                            700: '#B91C1C',    // 稍浅红色
                            800: '#991B1B',    // 深一点的红色
                            900: '#7F1D1D',    // 最深红色
                        }
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            /* 导航栏样式 */
            .nav-item {
                @apply flex flex-col items-center justify-center text-gray-300 active:bg-red-800 h-full;
            }
            .nav-item.active {
                @apply text-white;
            }
            .nav-icon {
                @apply text-lg mb-1;
            }
            .nav-text {
                @apply text-xs;
            }

            /* 表单样式 */
            .form-section {
                @apply bg-red-800 rounded-lg p-4 mb-4 border border-red-700;
            }
            .form-label {
                @apply block text-sm mb-2 font-medium;
            }
            .form-input {
                @apply w-full bg-red-900 border border-red-700 rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-secondary;
            }
            .upload-area {
                @apply w-full bg-red-900/50 border-2 border-dashed border-red-700 rounded p-4 text-center cursor-pointer hover:border-secondary transition-colors;
            }
            .file-info {
                @apply text-xs text-gray-200 mt-1;
            }

            /* 上传进度样式 */
            .progress-container {
                @apply w-full bg-red-800 rounded-full h-2 mt-2 hidden;
            }
            .progress-bar {
                @apply bg-secondary h-2 rounded-full transition-all duration-300;
            }
            .progress-text {
                @apply text-xs text-gray-300 mt-1 text-center;
            }
        }
    </style>
</head>
<body class="bg-primary text-white">
<div class="max-w-md mx-auto min-h-screen flex flex-col">
    <!-- 页面标题 -->
    <div class="py-4 px-4 border-b border-red-700 bg-red-900 flex justify-between items-center">
        <a href="#" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h1 class="text-xl font-bold">参赛报名表</h1>
        <span class="w-6"></span> <!-- 占位，保持标题居中 -->
    </div>

    <!-- 页面内容区 -->
    <div class="flex-1 overflow-y-auto p-4 pb-24">
        <!-- 表单说明 -->
        <div class="form-section">
            <p class="text-sm text-gray-100">
                请准确填写以下信息并上传相关材料，带 <span class="text-secondary">*</span> 的为必填项
            </p>
        </div>

        <!-- 作品信息 -->
        <div class="form-section">
            <h2 class="text-lg font-bold mb-4 flex items-center">
                <i class="fa fa-pencil-square-o mr-2 text-secondary"></i>作品信息
            </h2>

            <!-- 作品名称 -->
            <div class="mb-4">
                <label class="form-label">
                    作品名称 <span class="text-secondary">*</span>
                </label>
                <input type="text" class="form-input" placeholder="请输入作品名称" id="workName">
            </div>

            <!-- 作品封面 -->
            <div class="mb-4">
                <label class="form-label">
                    作品封面 <span class="text-secondary">*</span>
                </label>
                <div class="upload-area" id="coverUploadArea" onclick="document.getElementById('coverFile').click()">
                    <input type="file" accept="image/*" class="hidden" id="coverFile">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传作品封面图</p>
                    <p class="file-info">支持JPG、PNG格式，建议尺寸1080×720</p>
                    <div class="progress-container" id="coverProgressContainer">
                        <div class="progress-bar" id="coverProgressBar"></div>
                    </div>
                    <div class="progress-text" id="coverProgressText"></div>
                </div>
                <div id="coverMessage" class="text-xs mt-1"></div>
            </div>

            <!-- 作品简介 -->
            <div class="mb-4">
                <label class="form-label">
                    作品简介 <span class="text-secondary">*</span>
                </label>
                <textarea
                        class="form-input h-24 resize-none"
                        placeholder="请简要介绍您的作品，字数100字以内"
                        maxlength="100"
                        id="workIntro"
                ></textarea>
                <div class="text-right text-xs text-gray-300 mt-1">
                    <span id="wordCount">0</span>/100
                </div>
            </div>

            <!-- 联系人 -->
            <div class="mb-4">
                <label class="form-label">
                    联系人 <span class="text-secondary">*</span>
                </label>
                <input type="text" class="form-input" placeholder="请输入联系人姓名" id="contactName">
            </div>
        </div>

        <!-- 作品文件上传 -->
        <div class="form-section">
            <h2 class="text-lg font-bold mb-4 flex items-center">
                <i class="fa fa-file-text-o mr-2 text-secondary"></i>作品文件上传
            </h2>

            <!-- 微情景剧本 -->
            <div class="mb-4">
                <label class="form-label">
                    微情景剧本 <span class="text-secondary">*</span>
                </label>
                <div class="upload-area" id="scriptUploadArea" onclick="document.getElementById('scriptFile').click()">
                    <input type="file" accept=".doc,.docx" class="hidden" id="scriptFile">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传微情景剧本</p>
                    <p class="file-info">Word文档（.doc/.docx），不超过20MB</p>
                    <div class="progress-container" id="scriptProgressContainer">
                        <div class="progress-bar" id="scriptProgressBar"></div>
                    </div>
                    <div class="progress-text" id="scriptProgressText"></div>
                </div>
                <div id="scriptMessage" class="text-xs mt-1"></div>
            </div>

            <!-- 微情境视频 -->
            <div class="mb-4">
                <label class="form-label">
                    微情境视频 <span class="text-secondary">*</span>
                </label>
                <div class="upload-area" id="video1UploadArea" onclick="document.getElementById('video1File').click()">
                    <input type="file" accept=".mp4" class="hidden" id="video1File">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传微情境视频</p>
                    <p class="file-info">3-5分钟，MP4格式，分辨率不低于1080P，500MB以下</p>
                    <div class="progress-container" id="video1ProgressContainer">
                        <div class="progress-bar" id="video1ProgressBar"></div>
                    </div>
                    <div class="progress-text" id="video1ProgressText"></div>
                </div>
                <div id="video1Message" class="text-xs mt-1"></div>
            </div>

            <!-- 微宣讲视频 -->
            <div class="mb-4">
                <label class="form-label">
                    微宣讲视频 <span class="text-secondary">*</span>
                </label>
                <div class="upload-area" id="video2UploadArea" onclick="document.getElementById('video2File').click()">
                    <input type="file" accept=".mp4" class="hidden" id="video2File">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传微宣讲视频</p>
                    <p class="file-info">3-5分钟，MP4格式，分辨率不低于1080P，500MB以下</p>
                    <div class="progress-container" id="video2ProgressContainer">
                        <div class="progress-bar" id="video2ProgressBar"></div>
                    </div>
                    <div class="progress-text" id="video2ProgressText"></div>
                </div>
                <div id="video2Message" class="text-xs mt-1"></div>
            </div>

            <!-- 宣讲文稿 -->
            <div class="mb-4">
                <label class="form-label">
                    宣讲文稿 <span class="text-secondary">*</span>
                </label>
                <div class="upload-area" id="speechUploadArea" onclick="document.getElementById('speechFile').click()">
                    <input type="file" accept=".doc,.docx" class="hidden" id="speechFile">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传宣讲文稿</p>
                    <p class="file-info">Word文档（.doc/.docx），不超过20MB</p>
                    <div class="progress-container" id="speechProgressContainer">
                        <div class="progress-bar" id="speechProgressBar"></div>
                    </div>
                    <div class="progress-text" id="speechProgressText"></div>
                </div>
                <div id="speechMessage" class="text-xs mt-1"></div>
            </div>

            <!-- 其他附件 -->
            <div class="mb-4">
                <label class="form-label">
                    其他附件
                </label>
                <div class="upload-area" id="otherUploadArea" onclick="document.getElementById('otherFile').click()">
                    <input type="file" accept=".doc,.docx,.ppt,.pptx,.zip,.rar" class="hidden" id="otherFile">
                    <i class="fa fa-upload text-secondary text-xl mb-1"></i>
                    <p class="text-sm">点击上传其他附件（可选）</p>
                    <p class="file-info">支持word、ppt、zip等格式，不超过50MB</p>
                    <div class="progress-container" id="otherProgressContainer">
                        <div class="progress-bar" id="otherProgressBar"></div>
                    </div>
                    <div class="progress-text" id="otherProgressText"></div>
                </div>
                <div id="otherMessage" class="text-xs mt-1"></div>
            </div>
        </div>

        <!-- 免责声明 -->
        <div class="form-section">
            <div class="flex items-start mb-2">
                <input type="checkbox" id="agreement" class="mt-1 mr-2">
                <label for="agreement" class="text-sm">
                    我已阅读并同意<a href="/h5/index_mianze" class="text-secondary">《参赛作品免责声明》</a>，确认所提交的作品为原创作品，不侵犯任何第三方权益，如违反上述承诺，愿意承担相应法律责任。<span class="text-secondary">*</span>
                </label>
            </div>
        </div>

        <!-- 提交按钮 -->
        <div class="pt-2">
            <button id="submitBtn" class="w-full bg-secondary text-red-900 py-3 rounded font-medium text-sm opacity-50 cursor-not-allowed">
                提交报名
            </button>
        </div>
    </div>

    <!-- 底部固定导航栏 -->
    <div class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-red-900 border-t border-red-700 z-50 h-16 flex">
        <a href="/h5/index" class="nav-item active flex-1">
            <i class="nav-icon fa fa-home"></i>
            <span class="nav-text">首页</span>
        </a>
        <a href="/h5/index_huodong" class="nav-item flex-1">
            <i class="nav-icon fa fa-calendar"></i>
            <span class="nav-text">活动</span>
        </a>
        <a href="/h5/index_paihangbang" class="nav-item flex-1">
            <i class="nav-icon fa fa-bar-chart"></i>
            <span class="nav-text">排行榜</span>
        </a>
        <a href="/h5/index_yonghu" class="nav-item flex-1">
            <i class="nav-icon fa fa-user"></i>
            <span class="nav-text">我的</span>
        </a>
    </div>
</div>
<script src="../templates/h5/assets/jquery.min.js"></script>
<script src="../templates/h5/assets/aliyun-oss-sdk-6.18.0.min.js"></script>
<script src="../templates/h5/assets/vconsole.min.js"></script>
<script src="../templates/h5/assets/ossUpload.js"></script>
<script>
    // var vConsole = new VConsole();
    // console.log('Hello world');
</script>

<script>
    // 全局存储：保存所有表单数据
    let formData = {
        // 文本字段
        workName: '',
        workIntro: '',
        contactName: '',

        // 文件字段 - 每个文件保存URL和原始文件名
        workCover: { url: '', name: '' },
        workScript: { url: '', name: '' },
        workVideo1: { url: '', name: '' },
        workVideo2: { url: '', name: '' },
        workSpeech: { url: '', name: '' },
        workOther: { url: '', name: '' }
    };

    // 定位工具：打印当前触发的元素，方便排查重复绑定
    function logEvent(el, msg) {
        console.log(`[${new Date().getTime()}] ${msg}`, el);
    }

    $(function() {
        // -------------------------- 基础功能：字数统计和文本字段监听 --------------------------
        const $intro = $('#workIntro');
        $intro.on('input', function() {
            logEvent(this, '简介输入触发');
            const value = $(this).val();
            $('#wordCount').text(value.length);
            formData.workIntro = value;
            updateSubmitBtn();
        });

        // 作品名称监听
        $('#workName').on('input', function() {
            formData.workName = $(this).val().trim();
            updateSubmitBtn();
        });

        // 联系人监听
        $('#contactName').on('input', function() {
            formData.contactName = $(this).val().trim();
            updateSubmitBtn();
        });

        // -------------------------- 文件选择事件处理 --------------------------
        // 为每个文件输入框添加change事件处理
        $('#coverFile').on('change', function(e) {
            handleFileSelect(this, 'workCover');
        });
        $('#scriptFile').on('change', function(e) {
            handleFileSelect(this, 'workScript');
        });
        $('#video1File').on('change', function(e) {
            handleFileSelect(this, 'workVideo1');
        });
        $('#video2File').on('change', function(e) {
            handleFileSelect(this, 'workVideo2');
        });
        $('#speechFile').on('change', function(e) {
            handleFileSelect(this, 'workSpeech');
        });
        $('#otherFile').on('change', function(e) {
            handleFileSelect(this, 'workOther');
        });

        // -------------------------- 初始化OSS上传插件 --------------------------
        initUploader('coverFile', 'coverUploadArea', 'coverMessage', 'coverProgressContainer',
            'coverProgressBar', 'coverProgressText', 'workCover');
        initUploader('scriptFile', 'scriptUploadArea', 'scriptMessage', 'scriptProgressContainer',
            'scriptProgressBar', 'scriptProgressText', 'workScript');
        initUploader('video1File', 'video1UploadArea', 'video1Message', 'video1ProgressContainer',
            'video1ProgressBar', 'video1ProgressText', 'workVideo1');
        initUploader('video2File', 'video2UploadArea', 'video2Message', 'video2ProgressContainer',
            'video2ProgressBar', 'video2ProgressText', 'workVideo2');
        initUploader('speechFile', 'speechUploadArea', 'speechMessage', 'speechProgressContainer',
            'speechProgressBar', 'speechProgressText', 'workSpeech');
        initUploader('otherFile', 'otherUploadArea', 'otherMessage', 'otherProgressContainer',
            'otherProgressBar', 'otherProgressText', 'workOther');

        // -------------------------- 提交控制：按钮状态 --------------------------
        $('#agreement').on('change', function() {
            logEvent(this, '免责声明勾选触发');
            updateSubmitBtn();
        });

        // -------------------------- 最终提交：表单提交 --------------------------
        $('#submitBtn').on('click', function() {
            submitFinalData();
        });
    });

    /**
     * 处理文件选择事件
     */
    function handleFileSelect(input, fileField) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            logEvent(file, `${fileField} 文件选择触发`);
            const fileSize = (file.size / 1024 / 1024).toFixed(2);

            // 保存原始文件名到formData中（先保存文件名，URL等上传成功后再保存）
            formData[fileField].name = file.name;

            // 根据字段类型获取对应的消息容器ID
            const messageId = getMessageIdByField(fileField);

            $(`#${messageId}`).html(`
                <strong>文件信息:</strong><br>
                名称: ${file.name}<br>
                大小: ${fileSize} MB<br>
                类型: ${file.type || '未知'}<br>
                <span class="text-yellow-400">上传中...</span>
            `).show();

            console.log(`文件 ${fileField} 已选择，等待自动上传`);
        }
    }

    /**
     * 根据字段名获取对应的消息容器ID
     */
    function getMessageIdByField(field) {
        const fieldMap = {
            'workCover': 'coverMessage',
            'workScript': 'scriptMessage',
            'workVideo1': 'video1Message',
            'workVideo2': 'video2Message',
            'workSpeech': 'speechMessage',
            'workOther': 'otherMessage'
        };
        return fieldMap[field] || '';
    }

    /**
     * 根据字段名获取对应的进度条相关元素ID
     */
    function getProgressIdsByField(field) {
        const progressMap = {
            'workCover': {
                container: 'coverProgressContainer',
                bar: 'coverProgressBar',
                text: 'coverProgressText'
            },
            'workScript': {
                container: 'scriptProgressContainer',
                bar: 'scriptProgressBar',
                text: 'scriptProgressText'
            },
            'workVideo1': {
                container: 'video1ProgressContainer',
                bar: 'video1ProgressBar',
                text: 'video1ProgressText'
            },
            'workVideo2': {
                container: 'video2ProgressContainer',
                bar: 'video2ProgressBar',
                text: 'video2ProgressText'
            },
            'workSpeech': {
                container: 'speechProgressContainer',
                bar: 'speechProgressBar',
                text: 'speechProgressText'
            },
            'workOther': {
                container: 'otherProgressContainer',
                bar: 'otherProgressBar',
                text: 'otherProgressText'
            }
        };
        return progressMap[field] || {};
    }

    /**
     * 初始化OSS上传插件
     */
    function initUploader(fileId, areaId, messageId, progressContainerId, progressBarId, progressTextId, fileField) {
        $('#' + fileId).ossUpload({
            stsUrl: '/oss/getStsToken',
            dropArea: '#' + areaId,
            messageContainer: '#' + messageId,
            progressContainer: '#' + progressContainerId,
            progressBar: '#' + progressBarId,
            progressText: '#' + progressTextId,
            autoUpload: true,
            onFileSelect: function(file) {
                logEvent(file, `${fileField} 文件选择触发（插件内）`);
                const fileSize = (file.size / 1024 / 1024).toFixed(2);
                $('#' + messageId).html(`
                    <strong>文件信息:</strong><br>
                    名称: ${file.name}<br>
                    大小: ${fileSize} MB<br>
                    类型: ${file.type || '未知'}<br>
                    <span class="text-yellow-400">上传中...</span>
                `).show();
            },
            onProgress: function(percentage) {
                console.log(`${fileField} 上传进度:`, percentage);
                // 更新进度显示
                $('#' + progressBarId).css('width', percentage + '%');
                $('#' + progressTextId).text(`上传进度: ${percentage}%`);
            },
            onSuccess: function(result, fileName, uploadInfo) {
                logEvent(fileName, `${fileField} 上传成功`);
                console.log('上传成功:', uploadInfo);

                // 保存文件URL到对应的formData字段



                formData[fileField].url = "https://xjksii81ks.oss-cn-beijing.aliyuncs.com/" + uploadInfo.fileName;
                // 确保文件名也已保存（如果handleFileSelect中已经保存了）
                if (!formData[fileField].name) {
                    formData[fileField].name = fileName || '未知文件';
                }

                updateSubmitBtn();

                // 更新消息显示
                $('#' + messageId).html(`<span class="text-green-400">✅ 已上传: ${formData[fileField].name}</span>`);

                // 隐藏进度条
                $('#' + progressContainerId).hide();
                $('#' + progressTextId).text('');
            },
            onError: function(error) {
                console.error(`${fileField} 上传错误:`, error);
                $('#' + messageId).html(`<span class="text-red-400">❌ 上传失败: ${error.message || '未知错误'}</span>`);

                // 清除文件信息
                formData[fileField].url = '';
                formData[fileField].name = '';

                // 隐藏进度条
                $('#' + progressContainerId).hide();
                $('#' + progressTextId).text('');

                updateSubmitBtn();
            },
            onResult: function(uploadInfo) {
                console.log(`${fileField} 上传结果:`, uploadInfo);
            }
        });
    }

    /**
     * 更新提交按钮状态
     */
    function updateSubmitBtn() {
        logEvent('#submitBtn', '开始检查按钮状态');

        // 检查文本必填项
        const hasTextFields = formData.workName && formData.workIntro && formData.contactName;

        // 检查必传文件（只判断url是否有值）
        const hasRequiredFiles = formData.workCover.url &&
            formData.workScript.url &&
            formData.workVideo1.url &&
            formData.workVideo2.url &&
            formData.workSpeech.url;

        // 检查免责声明
        const isAgree = $('#agreement').is(':checked');

        // 所有条件满足则启用按钮
        const canSubmit = hasTextFields && hasRequiredFiles && isAgree;

        if (canSubmit) {
            $('#submitBtn').removeClass('opacity-50 cursor-not-allowed');
        } else {
            $('#submitBtn').addClass('opacity-50 cursor-not-allowed');
        }

        console.log('表单数据状态:', formData);
        logEvent('#submitBtn', `按钮状态更新：${canSubmit ? '可提交' : '禁用'}`);
    }

    /**
     * 最终提交表单
     */
    function submitFinalData() {
        logEvent('#submitBtn', '开始提交表单');
        // workName: $('input[placeholder="请输入作品名称"]').val().trim(),
        //     workIntro: $('textarea[maxlength="100"]').val().trim(),
        //     contactName: $('input[placeholder="请输入联系人姓名"]').val().trim(),
        //     // 只传OSS访问地址（如果后端需要objectKey，再从上传接口加回来）
        //     workCover: fileUrls.cover,
        //     workScript: fileUrls.script,
        //     workVideo1: fileUrls.video1,
        //     workVideo2: fileUrls.video2,
        //     workSpeech: fileUrls.speech,
        //     workOther: fileUrls.other
        // 组装提交数据 - 直接使用formData中的数据
        const submitData = {
            // workName: formData.workName,
            // workIntro: formData.workIntro,
            // contactName: formData.contactName,

            workName: $('input[placeholder="请输入作品名称"]').val().trim(),
            workIntro: $('textarea[maxlength="100"]').val().trim(),
            contactName: $('input[placeholder="请输入联系人姓名"]').val().trim(),
            // 文件URL字段
            workCover: formData.workCover.url,
            workScript: formData.workScript.url,
            workVideo1: formData.workVideo1.url,
            workVideo2: formData.workVideo2.url,
            workSpeech: formData.workSpeech.url,
            workOther: formData.workOther.url,
            // 文件名字段
            // workCoverName: formData.workCover.name,
            // workScriptName: formData.workScript.name,
            // workVideo1Name: formData.workVideo1.name,
            // workVideo2Name: formData.workVideo2.name,
            // workSpeechName: formData.workSpeech.name,
            // workOtherName: formData.workOther.name
        };
        console.log('提交的数据:', submitData);

        $.ajax({
            url: '/h5/comp/work/add',
            type: 'POST',
            data: JSON.stringify(submitData),
            contentType: 'application/json;charset=utf-8',
            beforeSend: function() {
                $('#submitBtn').text('提交中...').addClass('opacity-50 cursor-not-allowed');
            },
            success: function(res) {
                if (res && res.code == 0) {
                    alert('提交成功！');
                    window.location.href = '/h5/index';
                } else {
                    alert('提交失败，请完善并核对信息后重试～');
                    $('#submitBtn').text('提交报名').removeClass('opacity-50 cursor-not-allowed');
                }
            },
            error: function(xhr, status) {
                logEvent('#submitBtn', `提交报错：${status}`);
                alert('提交失败：网络错，请重试');
                $('#submitBtn').text('提交报名').removeClass('opacity-50 cursor-not-allowed');
            }
        });
    }
</script>
</body>
</html>